Coverage Report

Created: 2026-11-19 22:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
D:\a\cssh-rs\cssh-rs\cssh-rs-platform-windows\src\traits.rs
Line
Count
Source
1
//! Windows implementations of the `cssh-rs-platform` traits.
2
//!
3
//! The impls wrap the existing [`WindowsApi`] helpers and
4
//! `tokio::net::windows::named_pipe` so the daemon and client can be
5
//! ported to the platform-agnostic surface in later milestones. They are
6
//! not consumed by the M0 daemon/client yet; the trait surface is what
7
//! Linux and macOS stubs need to mirror.
8
//!
9
//! [`WindowsApi`]: crate::api::WindowsApi
10
11
use std::ffi::{OsStr, OsString};
12
use std::io;
13
use std::sync::Arc;
14
15
use cssh_rs_platform::{
16
    ControlChannelClient, ControlChannelServer, LaunchContext, ProcessSpawner, WindowHandleProbe,
17
};
18
use tokio::io::{AsyncReadExt, AsyncWriteExt, Interest};
19
use tokio::net::windows::named_pipe::{
20
    ClientOptions, NamedPipeClient, NamedPipeServer, PipeMode, ServerOptions,
21
};
22
use windows::Win32::Foundation::{CloseHandle, HANDLE, HWND};
23
use windows::Win32::System::Threading::PROCESS_INFORMATION;
24
25
use crate::api::{DefaultWindowsApi, WindowsApi};
26
27
/// `Send + Sync` wrapper around [`PROCESS_INFORMATION`].
28
///
29
/// [`PROCESS_INFORMATION`] is `!Send` because its `HANDLE` fields wrap raw
30
/// pointers. The handles are owned by the spawning process and remain valid
31
/// across thread boundaries, so the wrapper asserts thread safety with
32
/// `unsafe impl`. The daemon already uses the same pattern for
33
/// `Client::process_handle` via its private `HWNDWrapper`.
34
#[derive(Debug)]
35
pub struct SendProcessInformation(pub PROCESS_INFORMATION);
36
37
// SAFETY: PROCESS_INFORMATION's HANDLE fields are opaque kernel handles,
38
// not pointers into the calling thread's address space; the OS allows the
39
// owning process to use them from any thread.
40
unsafe impl Send for SendProcessInformation {}
41
// SAFETY: same justification as for `Send` - the handle values are immutable
42
// once `CreateProcessW` returns, so shared references can travel freely.
43
unsafe impl Sync for SendProcessInformation {}
44
45
impl Drop for SendProcessInformation {
46
3
    fn drop(&mut self) {
47
        // CreateProcessW returns kernel handles to the new process and its
48
        // primary thread; both must be closed to avoid leaking entries from
49
        // the per-process handle table. Skip NULL/invalid handles to avoid
50
        // the ERROR_INVALID_HANDLE that CloseHandle reports for them - see
51
        // https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle
52
6
        for handle in 
[self.0.hProcess, self.0.hThread]3
{
53
6
            if !handle.is_invalid() {
54
0
                // SAFETY: handle came from CreateProcessW (or a test-side
55
0
                // fake) and is not aliased anywhere else - the wrapper owns
56
0
                // it for its entire lifetime.
57
0
                let _ = unsafe { CloseHandle(handle) };
58
6
            }
59
        }
60
3
        self.0.hProcess = HANDLE::default();
61
3
        self.0.hThread = HANDLE::default();
62
3
    }
63
}
64
65
/// `Send + Sync` wrapper around [`HWND`].
66
///
67
/// Mirrors the daemon's private `HWNDWrapper` so the platform-trait
68
/// surface can be `Send + Sync` without consumers having to define their
69
/// own newtype.
70
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71
pub struct SendHwnd(pub HWND);
72
73
// SAFETY: HWND is an opaque user-mode kernel object identifier the OS lets
74
// any thread in the owning process consult.
75
unsafe impl Send for SendHwnd {}
76
// SAFETY: same justification as for `Send` - the underlying identifier is
77
// immutable and read-only from Rust's perspective.
78
unsafe impl Sync for SendHwnd {}
79
80
/// Windows-side [`LaunchContext`].
81
///
82
/// Carries the focus-handoff hint the daemon uses when spawning client
83
/// consoles. The current Win32 spawn path inspects the same flag to apply
84
/// `STARTF_USESHOWWINDOW` + `SW_SHOWNOACTIVATE`, so this field is the
85
/// minimum needed to round-trip today's behaviour through the trait.
86
#[derive(Debug, Clone, Copy, Default)]
87
pub struct WindowsLaunchContext {
88
    /// Whether the spawned console is allowed to take foreground focus.
89
    pub with_keyboard_focus: bool,
90
}
91
92
impl LaunchContext for WindowsLaunchContext {}
93
94
/// Process spawner backed by [`WindowsApi::create_process_with_os_args`].
95
///
96
/// Holds an [`Arc`] over a [`WindowsApi`] implementation so callers can
97
/// inject a mock in tests (the crate's `mock` feature exposes
98
/// `MockWindowsApi` for this purpose); production code uses
99
/// [`Self::default`] which selects [`DefaultWindowsApi`].
100
pub struct WindowsProcessSpawner<A: WindowsApi = DefaultWindowsApi> {
101
    api: Arc<A>,
102
}
103
104
impl<A: WindowsApi> WindowsProcessSpawner<A> {
105
    /// Construct a spawner around a specific [`WindowsApi`] implementation.
106
    ///
107
    /// # Arguments
108
    /// * `api` - Windows API operations implementation.
109
4
    pub fn new(api: Arc<A>) -> Self {
110
4
        return Self { api };
111
4
    }
112
}
113
114
impl Default for WindowsProcessSpawner<DefaultWindowsApi> {
115
1
    fn default() -> Self {
116
1
        return Self::new(Arc::new(DefaultWindowsApi));
117
1
    }
118
}
119
120
impl<A: WindowsApi + 'static> ProcessSpawner for WindowsProcessSpawner<A> {
121
    type Context = WindowsLaunchContext;
122
    type Handle = SendProcessInformation;
123
    type Error = io::Error;
124
125
3
    fn spawn(
126
3
        &self,
127
3
        program: &OsStr,
128
3
        args: &[OsString],
129
3
        context: &Self::Context,
130
3
    ) -> Result<Self::Handle, Self::Error> {
131
3
        return self
132
3
            .api
133
3
            .create_process_with_os_args(program, args, context.with_keyboard_focus)
134
3
            .map(SendProcessInformation)
135
3
            .map_err(|err| 
{1
136
                // The thread-local last-error code is what CreateProcessW
137
                // actually reports; the windows-rs `Error` typically just
138
                // re-wraps it but stringifies it as an opaque HRESULT.
139
1
                let os_err = io::Error::last_os_error();
140
1
                if os_err.raw_os_error().unwrap_or(0) != 0 {
141
1
                    return os_err;
142
0
                }
143
0
                return io::Error::other(format!("CreateProcessW failed: {err}"));
144
1
            });
145
3
    }
146
}
147
148
/// Return the named-pipe path of the control channel owned by a daemon.
149
///
150
/// # Arguments
151
/// * `pid` - Process id of the daemon.
152
///
153
/// # Returns
154
/// `\\.\pipe\cssh-rs-<pid>-control`.
155
1
pub fn control_endpoint(pid: u32) -> OsString {
156
1
    return OsString::from(format!(r"\\.\pipe\cssh-rs-{pid}-control"));
157
1
}
158
159
/// Daemon-side control channel backed by a Windows named pipe server.
160
///
161
/// One instance owns one [`NamedPipeServer`] endpoint. `accept`
162
/// waits for the matching client process to connect; `send` / `recv`
163
/// then exchange already-framed bytes produced by `cssh-rs-protocol`.
164
pub struct WindowsControlChannelServer {
165
    pipe: NamedPipeServer,
166
    endpoint: OsString,
167
}
168
169
impl WindowsControlChannelServer {
170
    /// Open a new named-pipe server endpoint at `endpoint`.
171
    ///
172
    /// # Arguments
173
    /// * `endpoint` - Fully-qualified Windows named-pipe name
174
    ///   (e.g. `\\.\pipe\cssh-rs-named-pipe-for-ipc`).
175
    ///
176
    /// # Returns
177
    /// Ready-to-`accept` server, or the underlying I/O error from
178
    /// [`ServerOptions::create`].
179
5
    pub fn bind(endpoint: &OsStr) -> io::Result<Self> {
180
5
        let pipe = ServerOptions::new()
181
5
            .access_inbound(true)
182
5
            .access_outbound(true)
183
5
            .pipe_mode(PipeMode::Message)
184
5
            .create(endpoint)
?0
;
185
5
        return Ok(Self {
186
5
            pipe,
187
5
            endpoint: endpoint.to_owned(),
188
5
        });
189
5
    }
190
191
    /// Endpoint name the server is bound to.
192
    ///
193
    /// # Returns
194
    /// The named-pipe path supplied to [`Self::bind`].
195
1
    pub fn endpoint(&self) -> &OsStr {
196
1
        return self.endpoint.as_os_str();
197
1
    }
198
199
    /// Test for pending readable bytes without blocking.
200
    ///
201
    /// # Returns
202
    /// `Ok(true)` when the pipe has bytes ready to read, `Ok(false)`
203
    /// otherwise, or the underlying I/O error.
204
1
    pub async fn ready_to_read(&mut self) -> io::Result<bool> {
205
1
        let ready = self.pipe.ready(Interest::READABLE).await
?0
;
206
1
        return Ok(ready.is_readable());
207
1
    }
208
209
    /// Write `frame` without waiting for the pipe to become writable.
210
    ///
211
    /// # Arguments
212
    /// * `frame` - Bytes to write.
213
    ///
214
    /// # Returns
215
    /// The number of bytes written, or the I/O error (`WouldBlock` when full).
216
4
    pub fn try_write(&self, frame: &[u8]) -> io::Result<usize> {
217
4
        return self.pipe.try_write(frame);
218
4
    }
219
}
220
221
impl ControlChannelServer for WindowsControlChannelServer {
222
    type Error = io::Error;
223
224
5
    async fn accept(&mut self) -> Result<(), Self::Error> {
225
5
        return self.pipe.connect().await;
226
5
    }
227
228
17
    async fn send(&mut self, frame: &[u8]) -> Result<(), Self::Error> {
229
17
        return self.pipe.write_all(frame).await;
230
17
    }
231
232
5
    async fn recv(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
233
5
        return self.pipe.read(buf).await;
234
5
    }
235
}
236
237
/// Client-side control channel backed by a Windows named pipe client.
238
pub struct WindowsControlChannelClient {
239
    pipe: Option<NamedPipeClient>,
240
}
241
242
impl WindowsControlChannelClient {
243
    /// Construct an unconnected control-channel client.
244
    ///
245
    /// # Returns
246
    /// A client whose `connect` has not yet run.
247
6
    pub fn new() -> Self {
248
6
        return Self { pipe: None };
249
6
    }
250
}
251
252
impl Default for WindowsControlChannelClient {
253
1
    fn default() -> Self {
254
1
        return Self::new();
255
1
    }
256
}
257
258
impl ControlChannelClient for WindowsControlChannelClient {
259
    type Error = io::Error;
260
261
5
    async fn connect(&mut self, endpoint: &OsStr) -> Result<(), Self::Error> {
262
5
        let pipe = ClientOptions::new().open(endpoint)
?0
;
263
5
        self.pipe = Some(pipe);
264
5
        return Ok(());
265
5
    }
266
267
6
    async fn send(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
268
6
        let 
pipe5
= self.pipe.as_mut().ok_or_else(||
{1
269
1
            return io::Error::other("control channel client is not connected");
270
1
        })?;
271
5
        return pipe.write_all(bytes).await;
272
6
    }
273
274
21
    async fn recv(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
275
21
        let 
pipe20
= self.pipe.as_mut().ok_or_else(||
{1
276
1
            return io::Error::other("control channel client is not connected");
277
1
        })?;
278
20
        return pipe.read(buf).await;
279
21
    }
280
}
281
282
/// Window-handle probe backed by [`WindowsApi::get_window_handle_for_process`].
283
///
284
/// Holds an [`Arc`] over a [`WindowsApi`] for the same testability reasons
285
/// as [`WindowsProcessSpawner`].
286
pub struct WindowsWindowHandleProbe<A: WindowsApi = DefaultWindowsApi> {
287
    api: Arc<A>,
288
}
289
290
impl<A: WindowsApi> WindowsWindowHandleProbe<A> {
291
    /// Construct a probe around a specific [`WindowsApi`] implementation.
292
    ///
293
    /// # Arguments
294
    /// * `api` - Windows API operations implementation.
295
3
    pub fn new(api: Arc<A>) -> Self {
296
3
        return Self { api };
297
3
    }
298
}
299
300
impl Default for WindowsWindowHandleProbe<DefaultWindowsApi> {
301
1
    fn default() -> Self {
302
1
        return Self::new(Arc::new(DefaultWindowsApi));
303
1
    }
304
}
305
306
impl<A: WindowsApi + 'static> WindowHandleProbe for WindowsWindowHandleProbe<A> {
307
    type Handle = SendHwnd;
308
309
2
    fn window_handle_for_process(&self, pid: u32) -> Option<Self::Handle> {
310
2
        let handle = self.api.get_window_handle_for_process(pid);
311
2
        if self.api.is_window(handle) {
312
1
            return Some(SendHwnd(handle));
313
1
        }
314
1
        return None;
315
2
    }
316
}
317
318
#[cfg(test)]
319
#[path = "tests/test_traits.rs"]
320
mod test_mod;